package com.alibaba.csp.sentinel.dashboard.rule.database.base;

import com.alibaba.csp.sentinel.dashboard.rule.database.enums.DatabaseRuleEnums;
import com.alibaba.csp.sentinel.dashboard.repository.dao.SqlHelper;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

import javax.swing.table.DefaultTableModel;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Component
public abstract class BaseDatabaseRuleProvider implements DynamicRuleProvider {


    @Override
    public List getRules(String appName) throws Exception {
        DatabaseRuleEnums flowDataId = getDataId();
        String rules = getRulesFromDB(appName, flowDataId);
        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }
        return JSON.parseArray(rules, getRuleClazz());
    }

    /**
     *
     * @return
     */
    protected abstract DatabaseRuleEnums getDataId();

    /**
     * 获取流控规则对应clazz，JSON转换用
     *
     * @return
     */
    protected abstract Class getRuleClazz();

    /**
     *
     * @param appName
     * @param dataId
     * @return
     */
    protected String getRulesFromDB(String appName, DatabaseRuleEnums dataId) {
        DefaultTableModel resultSet = SqlHelper.getResultSet("SELECT `content` FROM   `cc_sentinel_rule`\n" +
                "WHERE `app_name`='" + appName + "' AND `rule_type`=" + dataId.getCode());
        String content = null;

        try {
            content = resultSet.getValueAt(0, 0).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return content;
    }

}
